package mylab.starters.dag;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

import cn.hutool.core.collection.CollUtil;
import lombok.Getter;
import lombok.Setter;
import mylab.starters.dag.graph.Graph;

/**
 * DAG上下文:上下文的生命周期是引擎执行期间，即从开始节点到结束节点之间
 */
@SuppressWarnings("all")
public class DagContext {

    @Getter
    Graph graph;

    @Getter
    final Map<String, TaskResult<?>> resultMap = new ConcurrentHashMap<>();

    @Getter
    final Map<String, Thread> threadMap = Maps.newConcurrentMap();

    @Getter
    @Setter
    CountDownLatch syncLatch;

    @Getter
    @Setter
    ExecutorService executorService;

    public DagContext(Graph graph) {
        this.graph = graph;
        syncLatch = new CountDownLatch(graph.size());
    }

    public void putTaskResult(String taskId, TaskResult<?> taskResult) {
        resultMap.put(taskId, taskResult);
    }

    public TaskResult<?> getTaskResult(String taskId) {
        return resultMap.get(taskId);
    }

    public void putTaskThread(String taskId, Thread thread) {
        threadMap.put(taskId, thread);
    }

    public void removeTaskThread(String taskId) {
        threadMap.remove(taskId);
    }

    public void interruptThread() {
        if (CollUtil.isNotEmpty(threadMap)) {
            for (Thread thread : threadMap.values()) {
                thread.interrupt();
            }
        }
        threadMap.clear();
    }

}